from locust import HttpUser,task,constant,TaskSet,SequentialTaskSet
import json


@task # 第二种写法，定义在模块中,写一个函数，传入user对象，参数名任意
def get_all_list(user):
    all_list = '/app/room/list/v2.htm'
    r = user.client.get('/app/room/list/v2.htm',name = "获取所有主播v2.htm")
    if r.status_code == 200:
        print(r.url)
        # print(r.text)
    else:
        print("failed")




# 任务继承SequentialTaskSet,表示里面的任务是顺序执行
# 执行顺序：get_roomid  ---> get_roomInfo
class pplbsSeqTask(SequentialTaskSet):

    data_body = {}
    @task(1)  #  数字是执行的次数，执行1次
    def get_roomid(self):
        hot_path = "/app/room/hot/v2.htm"
        r = self.client.get(hot_path)
        print(r.url)
        r_data = r.json()
        roomId = r_data.get("data").get("sections")[0].get("items")[0].get("roomInfo").get("id")
        self.data_body["roomId"] = roomId



    @task(30) #  数字是执行的次数，执行30次
    def get_roomInfo(self):
        roomInfo_path = "https://pplbs.suning.com/app/room/in.htm"
        r = self.client.get(roomInfo_path,params=self.data_body)
        print(r.url)
        if r.status_code == 200:
            print(json.dumps(r.json(), ensure_ascii=False, indent=4))
        else:
            print("failed")






# task 第三种写法,定义任务集合类，集成TaskSet,所有的任务都在此类中执行,
# 任务是并行
class pplbsTask(TaskSet):

    @task
    def get_hot_list(self):
        hot_path = "/app/room/hot/v2.htm"
        r = self.client.get(hot_path)
        if r.status_code == 200:
            print(r.url)
            # print(r.text)
        else:
            print("failed")


# 定义用户类，继承HttpUser,因为我们测试的是http协议，所有locust已经封装好了HttpUser；
# 实际上HttpUser 继承User, 如果想测试其他的协议，可以自己开发继承User
class getPplbsUser(HttpUser):
    host = "https://pplbs.suning.com"  # 设置
    wait_time = constant(3) #每次请求的间隔，思考时间
    tasks = [get_all_list,pplbsTask,pplbsSeqTask]  # user 中定义执行的任务，是个列表，其中可以是一个函数名，也可以是类名


    @task  # 任务写法1：在User类中编写
    def get_nav(self):
        nav_path = "/app/room/nav.htm"

        r = self.client.get(nav_path, name = "获取皮球导航nav.htm")

        if r.status_code == 200:
            print(r.url)
            # print(r.text)
        else:
            print("failed")

if __name__ == '__main__':
    import os
    os.system("locust -f locust_demo.py")